//同时发送异步代码的次数
let ajaxTimes = 0;

export const request = (params) => {
    ajaxTimes++;

    //显示加载中效果
    wx.showLoading({
        title: '加载中',
        mask: true
    });

    //判断Url中是否带有 /my/ 请求的是私有路径 带上 header token
    const header = params.header ? {...params.header} : {};
    if (params.url.includes('/my/')) {
        header['Authorization'] = wx.getStorageSync('token');
    }

    //定义公共url
    const baseUrl = 'https://api-hmugo-web.itheima.net/api/public/v1';
    return new Promise((resolve, reject) => {
        wx.request({
            ...params,
            header,
            url: baseUrl + params.url,
            success: (result) => {
                const res = result.data ? (result.data.message ? result.data.message : result.data) : result;
                resolve(res);
            },
            fail: (err) => {
                reject(err);
            },
            complete(res) {
                ajaxTimes--;
                if (ajaxTimes === 0) {
                    wx.hideLoading();
                }
            }
        });
    });
};
